package com.mgiandia.library.jpadao;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.mgiandia.library.dao.LoanDAO;
import com.mgiandia.library.domain.core.Loan;



class LoanJpaDAO extends GenericJpaDAO<Loan> implements LoanDAO {

    public List<Loan> findAll() {
        CriteriaBuilder builder = JPAUtil.getEntityManagerFactory().getCriteriaBuilder();
        CriteriaQuery<Loan> criteria = builder.createQuery( Loan.class );
        Root<Loan> loan = criteria.from( Loan.class );
        criteria.select(loan);
        return JPAUtil.getCurrentEntityManager().createQuery(criteria).getResultList();     
    }


    @SuppressWarnings("unchecked")
    public List<Loan> findAllPending() {
        String jpql = "select l from Loan l where l.returnDate is null";
        Query qry = JPAUtil.getCurrentEntityManager().createQuery(jpql); 
        return  qry.getResultList();                
    }

    public Loan findPending(int itemNo) {
        try {
            String jpql = "select l from Loan l where l.item.itemNumber = :itemid and l.returnDate is null";
            Query qry = JPAUtil.getCurrentEntityManager().createQuery(jpql).setParameter("itemid", itemNo);
            return (Loan) qry.getSingleResult();            
        } catch (NoResultException ex) {
            return null;
        }
    }

}
